const mysql = require('mysql')
const config = require('./defaultConfig')

// 创建线程池
let pool = mysql.createPool({
  host: config.dataBase.HOST,
  user: config.dataBase.USERNAME,
  password: config.dataBase.PASSWORD,
  database: config.dataBase.DATABASE,
  port: config.dataBase.PORT,
})

// 连接线程池，做sql查找
let allServices = {
  query: function (sql, values) {
    return new Promise((resolve, reject) => {
      pool.getConnection(function (err, connection) {
        if (err) {
          reject(err)
        } else { // 连接成功
          connection.query(sql, values, (err, rows) => { // sql查找
            if (err) {
              reject(err)
            } else {
              resolve(rows)
            }
            connection.release()
          })
        }
      })
    })
  }
}

// 用户登录
let userLogin = function (username, userpwd) {
  let _sql = `select * from users where username="${username}" and userpwd="${userpwd}";`
  return allServices.query(_sql)
}

let findUser = function (username) {
  let _sql = `select * from users where username="${username}"; `
  return allServices.query(_sql)

}

let insertUser = function (value) {
  let _sql = `insert into users set username=?,userpwd=?,nickname=?;`
  return allServices.query(_sql, value)
}

let findNoteListByType = function (type) {
  let _sql = `SELECT * FROM note WHERE note_type="${type}";`
  return allServices.query(_sql)
}

let findNoteDetailById = function (id) {
  let _sql = `SELECT * FROM note WHERE id="${id}";`
  return allServices.query(_sql)
}


let insertNote = function(options){
  let _sql = `INSERT INTO note SET c_time=?,m_time=?,note_content=?,head_img=?,title=?,note_type=?,useId=?,nickname=?;`
  return allServices.query(_sql,options)
}

module.exports = {
  userLogin,
  insertUser,
  findUser,
  findNoteListByType,
  findNoteDetailById,
  insertNote
}

